package com.genius.aspect;

import com.genius.annotation.PreFuncAuth;
import com.genius.annotation.PreLoginAuth;
import com.genius.utils.AuthUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * PreAuthorizeAAOP的注解鉴权
 */
@Aspect
@Component
public class PreFuncAuthAspect {

    /**
     * 构建
     */
    public PreFuncAuthAspect() {
    }

    /**
     * 环绕通知
     * @param joinPoint 切面对象
     * @return 底层方法执行后的返回值
     * @throws Throwable 底层方法抛出的异常
     */
    @Around("@annotation(com.genius.annotation.PreLoginAuth) || @annotation(com.genius.annotation.PreFuncAuth)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 注解鉴权
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        checkMethodAnnotation(signature.getMethod());
        // 执行原有逻辑
        return joinPoint.proceed();
    }

    /**
     * 对Method对象进行权限校验
     */
    public void checkMethodAnnotation(Method method) {

        PreLoginAuth preLogin = method.getAnnotation(PreLoginAuth.class);
        if (preLogin != null) {
            AuthUtils.checkLogin();
        }

        PreFuncAuth preFuncAuth = method.getAnnotation(PreFuncAuth.class);
        if (preFuncAuth != null) {
            AuthUtils.checkLogin();
            AuthUtils.checkAuthority(preFuncAuth);
        }
    }
}
